package com.example.kafkademo.producer;

import org.apache.kafka.clients.producer.*;

import java.util.Properties;

/**
 * @author: HuangSiBo
 * @Description:异步发送消息，带回调函数
 * @Data: Created in 21:54 2021/12/26
 */
public class CallBackProducer {

    public static void main(String[] args) {
        Properties properties = new Properties();
        //连接的集群
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,"110.42.176.63:9092");
        //key，value的序列化
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");

        KafkaProducer kafkaProducer = new KafkaProducer(properties);

        for (int i = 0; i < 10; i++) {
            kafkaProducer.send(new ProducerRecord("first", Integer.toString(i), Integer.toString(i)), (metadata, exception) -> {
                System.out.println("partition: " + metadata.partition());
                System.out.println("offset: " + metadata.offset());
            });
        }

        //关闭生产者
        kafkaProducer.close();
    }
}
